/**
 * Created by JustinChow on 2016/11/14.
 */

"use strict";

const Logger = require("pomelo-logger").getLogger("BotHandler", __filename);

const BotPlayerPreset = require("../Configs/BotPlayerPreset.json");
const APIStaticConfig = require("../Configs/APIStaticConfig.json");

const BotPlayer     = require("./BotPlayer");
const Socket        = require("./FakeWebSocket");

const PacketHandler = require("../Utils/PacketHandler");

function BotHandler(gameServer) {
    this.gameServer = gameServer;
    this.config = BotPlayerPreset;

    this.lastBotId = 1;
}

module.exports = BotHandler;

BotHandler.prototype.addBot = function (presetId) {
    // TODO Use Preset Id To Create Bot With Different IQ
    var socket = new Socket(this.gameServer);
    socket.packetHandler = new PacketHandler(this.gameServer, socket);
    socket.playerTracker = new BotPlayer(this.gameServer, socket);

    this.gameServer.clients.push(socket);
    this.gameServer.userHandler.addClient(socket);

    socket.packetHandler.socket.protocolVersion = 5;
    this.gameServer.spawnPlayer(socket.playerTracker);
    socket.playerTracker.player.isBot = true;

    // Logger.debug("Auto Add Server Default Bot Success! [ %s ]", presetId);

    // AUTO DEBUG IF ADD AND REMOVE ARE ALL RIGHT!!!
    // setTimeout(function () {
    //     Logger.debug("Start To Remove Bot");
    //     this.removeBot();
    // }.bind(this), 10 * 1e3);

    // Todo: WARNING !!!! NOT WORKING WELL !!!
    // if (BotPlayerPreset.auto_remove) {
    //     setTimeout(function () {
    //         this.gameServer.botHandler.removeBot();
    //         if (BotPlayerPreset.auto_restart) this.gameServer.botHandler.addBot();
    //     }.bind(this), BotPlayerPreset.life_time);
    // }
};

BotHandler.prototype.removeBot = function (toRemove) {
    if (!toRemove || typeof toRemove != "number" || toRemove <= 1) toRemove = 1;

    var removed = 0, objectIds = [];
    for (let cid = 0, clen = this.gameServer.clients.length; cid < clen; cid++){
        let client = this.gameServer.clients[cid];
        if (removed < toRemove && client.playerTracker.player.isBot) {
            var objectId = client.playerTracker.player.objectId;
            objectIds.push(objectId);

            this.gameServer.removeNode(client.playerTracker.player);

            var index = this.gameServer.clients.indexOf(client);
            if (index != -1) this.gameServer.clients.splice(index, 1);

            client.playerTracker.fullyDisconnected = true;

            Logger.debug("Remove Server Default Bot [ %s ] Success!", objectId);
            removed += 1;
        }
    }

    Logger.info("Remove Server Bot Total: [ %s ] => ObjectIds: [ %s ]", removed, objectIds);
};
